import { ReactElement, useState, useEffect } from "react"
import style from './index.module.less'
import { companyName, appName, companyUrl, version } from '@js/config'
import { Checkbox, Button, message, Popover, Input, Space } from 'antd'
import UsernameForm from './components/usernameForm'
import PhoneForm from './components/phoneForm'
import logoBg from '@imgs/logoBg.png'
import telZone, { ZoneSchema } from '@js/telZone'
import { loginByUsernameRequest, loginByPhoneRequest } from './ajax'
import { awaitWrap } from "@src/assets/js/tool"
import { useNavigate, NavigateFunction } from 'react-router-dom'
import { useDispatch } from 'react-redux';
import { Dispatch } from "redux"
import { setUserInfo, setToken } from '@redux/actions/basic'
const zoneTelList: string[] = []
telZone.forEach(l => zoneTelList.push(l.tel))

async function loginHandle (
  isLoginByPassword: boolean,
  username: string,
  password: string,
  zoneNum: string,
  mobile: string,
  verification: string,
  setNoticeUsername: (v: string) => void,
  setNoticePassword: (v: string) => void,
  setNoticeMobile: (v: string) => void,
  setNoticeVerification: (v: string) => void,
  navigate: NavigateFunction,
  dispatch: Dispatch
) {
  if (isLoginByPassword) {
    if (!validateUsername(username, setNoticeUsername) || !validatePassword(password, setNoticePassword)) {
      return false
    }
    loginByUsername(username, password, navigate, dispatch)
  } else {
    if (!validateZoneTel(zoneNum, setNoticeMobile) || !validateMobile(mobile, setNoticeMobile) || !validateVerification(verification, setNoticeVerification)) {
      return false
    }
    loginByPhone(zoneNum, mobile, verification, navigate, dispatch)
  }
}

async function loginByUsername (username: string, password: string, navigate: NavigateFunction, dispatch: Dispatch) {
  const hide = message.loading('登录中', 120)
  const [e, d] = await awaitWrap(loginByUsernameRequest(username, password))
  hide()
  if (e === null && d !== null) {
    const { userInfo, token } = d
    dispatch(setUserInfo(userInfo))
    dispatch(setToken(token))
    message.success('登录成功', 2, () => {
      navigate('/admin')
    })
  }
}

async function loginByPhone (zoneNum: string, mobile: string, verification: string, navigate: NavigateFunction, dispatch: Dispatch) {
  const hide = message.loading('登录中', 120)
  const [e, d] = await awaitWrap(loginByPhoneRequest(zoneNum, mobile, verification))
  hide()
  if (e === null && d !== null) {
    const { userInfo, token } = d
    dispatch(setUserInfo(userInfo))
    dispatch(setToken(token))
    message.success('登录成功', 2, () => {
      navigate('/admin')
    })
  }
}

// 验证区号
function validateZoneTel (zoneNum: string, setNoticeMobile: (v: string) => void): boolean {
  if (!zoneNum) {
    setNoticeMobile('国际区号不能为空')
    return false
  }
  if (zoneTelList.indexOf(zoneNum) === -1) {
    setNoticeMobile('国际区号不存在')
    return false
  }
  setNoticeMobile('')
  return true
}

  // 验证手机号格式
function validateMobile (mobile: string, setNoticeMobile: (v: string) => void) {
  if (!mobile) {
    setNoticeMobile('手机号不能为空')
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    setNoticeMobile('手机号格式不正确')
    return false
  }
  setNoticeMobile('')
  return true
}

// 验证验证码
function validateVerification (verification: string, setNoticeVerification: (v: string) => void) {
  if (!verification) {
    setNoticeVerification('验证码不能为空')
    return false
  }
  if (!/^\d{4}$/.test(verification)) {
    setNoticeVerification('验证码格式不正确')
    return false
  }
  setNoticeVerification('')
  return true
}

 // 验证账号
function validateUsername (username: string, setNoticeUsername: (v: string) => void) {
  if (!username) {
    setNoticeUsername('账号不能为空')
    return false
  }
  setNoticeUsername('')
  return true
}

  // 验证密码
function validatePassword (password: string, setNoticePassword: (v: string) => void) {
  if (!password) {
    setNoticePassword('密码不能为空')
    return false
  }
  setNoticePassword('')
  return true
}

function Main (): ReactElement {
  const navigate = useNavigate()
  const [agree, setAgree] = useState(true)
  const [isLoginByPassword, setIsLoginByPassword] = useState(true)
  const [noticeUsername, setNoticeUsername] = useState('')
  const [noticePassword, setNoticePassword] = useState('')
  const [noticeMobile, setNoticeMobile] = useState('')
  const [noticeVerification, setNoticeVerification] = useState('')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [zoneNum, setZoneNum] = useState('86')
  const [mobile, setMobile] = useState('')
  const [verification, setVerification] = useState('')
  const [disabled, setDisabled] = useState(false)
  const dispatch = useDispatch()
  function login () {
    if (agree) {
      loginHandle(isLoginByPassword, username, password, zoneNum, mobile, verification, setNoticeUsername, setNoticePassword, setNoticeMobile, setNoticeVerification, navigate, dispatch)
    }
  }
  useEffect(() => {
    if (isLoginByPassword) {
       setDisabled(!username || !password || !agree)
    } else {
      setDisabled(!mobile || !zoneNum || !verification || !agree)
    }
  }, [username, mobile, zoneNum, verification, password, agree, isLoginByPassword])
  return (
    <div className={style.login}>
      <div className={style['login-right-block']}>
        <img src={logoBg} />
      </div>
      <div className={style['login-content']}>
        <div className={style['login-content__header']}>
          <span>{appName}</span>
        </div>
        <div className={style['login-content__block']}>
          <div className={style['login-content__form']}>
            <div className={style['login-content__form__h1']}>
              <span>登录</span>
            </div>

            <div className={style['login-content__form__h2']}>
              <span>
                {isLoginByPassword ? '请使用账号密码登录系统' : '请使用手机号获取验证码登录系统'}
              </span>
            </div>

            <div className={style['white-space']} />

            {
              isLoginByPassword ? (
                <UsernameForm username={username} setUsername={setUsername} password={password} setPassword={setPassword} noticeUsername={noticeUsername} noticePassword={noticePassword} login={() => login()} />
              ) : (
                <PhoneForm zoneNum={zoneNum} setZoneNum={setZoneNum} verification={verification} setVerification={setVerification} mobile={mobile} setMobile={setMobile} noticeMobile={noticeMobile} setNoticeMobile={setNoticeMobile} noticeVerification={noticeVerification} login={() => login()} />
              )
            }

            <div className={style['login-toggle-type']}>
              <span onClick={() => setIsLoginByPassword(!isLoginByPassword)}>
                {isLoginByPassword ? '手机验证码登录' : '账号密码登录'}
              </span>
            </div>

            <div className={style['protocol-block']}>
              <Checkbox checked={agree} onChange={(e) => setAgree(e.target.checked)} className={style['protocol-checkbox']} />
              <span onClick={() => setAgree(!agree)}>
                <span>我同意{companyName}使用我所提交的手机号用于快捷注册/登录。查看</span>
                <span className={style['protocol-link']}>《用户服务协议》</span>
                <span>及</span>
                <span className={style['protocol-link']}>《隐私政策》</span>
              </span>
            </div>

            <div className={style['btn-line']}>
              <Button className={style['login-btn']} disabled={disabled} type='primary' block onClick={() => login()}>登录</Button>
            </div>

          </div>
        </div>
        <div className={style['login-content__footer']}>
          <Space>
            <span>{companyName}</span>
            <span>{companyUrl}</span>
            <span>{version}</span>
          </Space>
        </div>
      </div>
    </div>
  )
}

export default Main

